package controllers

import (
	"github.com/astaxie/beego"
	"luckapi/mutils"
	"luckapi/models"
	"luckapi/mhandle"
	"encoding/json"
)

type GameController struct {
	beego.Controller
}

func (c *GameController) UrlMapping()  {
	c.Mapping("gamelist", c.GameList)
	c.Mapping("gamejoiner",c.JoinGame)
}

// GameList ...
// @Title GameList
// @Description gamelist
// @Param	body		body 	models.User	true		"body for User content"
// @Success 201 {int} models.User
// @Failure 403 body is empty
// @router /gamelist [post]
func (c *GameController) GameList() {
	mutils.MLog(string(c.Ctx.Input.RequestBody))

	err ,games := models.GetGameListOpen()
	if err.Code != mutils.ResponseCode_Success || len(games) == 0 {
		c.Data["json"] = map[string]interface{}{"code":err.Code,"message":err.Message,"data":map[string]interface{}{}}
	}else {
		c.Data["json"] = map[string]interface{}{"code":mutils.ResponseCode_Success,"message":err.Message,"data":map[string]interface{}{"gamelist":games}}
	}
	c.ServeJSON()
}

// JoinGame ...
// @Title JoinGame
// @Description joingame
// @Param	body		body 	models.User	true		"body for User content"
// @Success 201 {int} models.User
// @Failure 403 body is empty
// @router /joingame [post]
func (c *GameController) JoinGame() {
	mutils.MLog(string(c.Ctx.Input.RequestBody))
	var res map[string]int
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &res); err == nil {

		gameid := res["gameid"]
		userid := res["userid"]
		game := models.Game{Id:gameid}
		user := models.User{Id:userid}

		result  := mhandle.AllotLuckNum(game, user)

		if result == nil {
			c.Data["json"] = map[string]interface{}{"code":mutils.ResponseCode_Success,"message":"Success"}
		} else {
			c.Data["json"] = map[string]interface{}{"code":1,"message":result,"data":map[string]interface{}{}}
		}
	}else {
		c.Data["json"] = map[string]interface{}{"code":mutils.ErrorCode_Req_Parmas_NoMatch,"message":"Success"}
	}

	c.ServeJSON()
}